package com.sx.micowell.module.course.video

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.bumptech.glide.Glide
import com.dou361.ijkplayer.widget.MyPlayerView
import com.dou361.ijkplayer.widget.PlayStateParams
import com.example.mvvm.base.ContainerActivity
import com.example.mvvm.base.data.DataBindingConfig
import com.example.mvvm.until.LogUtils
import com.example.mvvm.until.ToastUtils
import com.gyf.immersionbar.ImmersionBar
import com.lxj.xpopup.XPopup
import com.miloyu.modelnet.response.CourseDetailList
import com.miloyu.modelnet.response.CourseVideoVO
import com.miloyu.modelnet.response.getUrl
import com.sx.micowell.R
import com.sx.micowell.databinding.FragCourseVideoPlayBinding
import com.sx.micowell.framework.app.IntentKey
import com.sx.micowell.framework.app.MyApplication
import com.sx.micowell.framework.app.MyFragment
import com.sx.micowell.framework.arouth.RouteManager
import com.sx.micowell.framework.arouth.RoutePath

/**
 * @Author: YY
 * @Time: 2021/9/14
 * @Describe TODO
 */
@Route(path = RoutePath.COURSE_VIDEO_PLAY)
class CourseVideoPlayFragment : MyFragment<FragCourseVideoPlayBinding, ContainerActivity>() {

    @Autowired(name = IntentKey.DATA)
    @JvmField
    var courseVideoData: CourseVideoVO? = null

    private var player: MyPlayerView ?=null

    var playIndex = 0

    var trainTime: Long = 0

    lateinit var actionVideoListAdapter: ActionVideoListAdapter

    override fun getDataBindingConfig(): DataBindingConfig {
        return DataBindingConfig(R.layout.frag_course_video_play)
    }

    override fun initView() {
        ImmersionBar.with(this).statusBarColor("#333333")
            .fitsSystemWindows(true).init()
        player?.let {
            it.videoView.setOnCompletionListener {
                trainTime += it.duration
                if (playIndex < courseVideoData!!.detail.size) {
                    // 播放视频
                    startPlay(
                        courseVideoData!!.detail[playIndex].url.getUrl(),
                        courseVideoData!!.detail[playIndex].cover.getUrl()
                    )
                } else {
                    LogUtils.d("setOnCompletionListener 结束")
                    val bundle = Bundle()
                    bundle.putLong(IntentKey.KEY, trainTime)
                    bundle.putSerializable(IntentKey.DATA, courseVideoData)
                    startContainerActivity(
                        RouteManager.getInstance().getCourseTrainEndFragment(
                            trainTime,
                            courseVideoData!!
                        ).javaClass.canonicalName,
                        bundle
                    )
                    mActivity.finish()
                }
            }
        }

    }

    override fun initData() {
        hideActionList()
        initPlayer()
        if (courseVideoData != null) {
            // 播放视频
            startPlay(
                courseVideoData!!.detail[playIndex].url.getUrl(),
                courseVideoData!!.detail[playIndex].cover.getUrl()
            )

            setActionList()
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        player?.onDestroy()
    }

    /**初始化播放视频*/
    private fun initPlayer() {

        player = MyPlayerView(activity)
            .setScaleType(PlayStateParams.fitparent)
            .forbidTouch(false)
            .hideHideTopBar(true)
            .hideSteam(true)
            .hideFullscreen(true)
            .hideRotation(true)
            .hideBottonBar(true)
            .hideHideTopBar(false)
            .setForbidDoulbeUp(true)
            .setPlayerBackListener {
                LogUtils.d("onPlayerBack")
                XPopup.Builder(myActivity).asConfirm(
                    "提示", "训练时间过短, 无法保存记录, \n再坚持一下",
                    "结束训练", "再练一会",
                    null, {
                        myActivity.finish()
                    }, false
                ).show()
            }

    }

    /**开始播放视频*/
    @SuppressLint("NotifyDataSetChanged")
    fun startPlay(mp4: String, bg: String) {
        context?.let {
            player?.showThumbnail { ivThumbnail ->
                Glide.with(it)
                    .load(bg)
                    .placeholder(R.color.black)
                    .error(R.color.black)
                    .into(ivThumbnail)
            }?.setPlaySource(MyApplication.instance().getProxy(it)?.getProxyUrl(mp4))
                ?.startPlay()
            playIndex++
        }

        player?.setNextListener {
            LogUtils.d("setNextListener")
            if (playIndex < courseVideoData!!.detail.size) {
                ToastUtils.showShort("正在切换下一个")
                actionVideoListAdapter.selectIndex = playIndex
                actionVideoListAdapter.notifyDataSetChanged()
                player?.setPlaySource(courseVideoData!!.detail[playIndex].url.getUrl())?.startPlay()
                playIndex++
            }
        }

        player?.setUpperListener {
            LogUtils.d("upperClick")
            if (playIndex > 1) {
                ToastUtils.showShort("正在切换上一个")
                playIndex--
                actionVideoListAdapter.selectIndex = playIndex - 1
                actionVideoListAdapter.notifyDataSetChanged()
                // 播放视频
                player?.setPlaySource(courseVideoData!!.detail[playIndex - 1].url.getUrl())
                    ?.startPlay()

            }
        }

        player?.setPlayListListener {
            LogUtils.d("展开列表")
            showActionList()
        }

    }

    private fun setActionList() {
        //取消recyclerview单独的滑动效果
        binding.recyclerAction.isNestedScrollingEnabled = false
        //设置布局管理器
        binding.recyclerAction.layoutManager = LinearLayoutManager(context)

        actionVideoListAdapter = ActionVideoListAdapter()
        actionVideoListAdapter.data = courseVideoData?.detail as MutableList<CourseDetailList>
        binding.recyclerAction.adapter = actionVideoListAdapter

        actionVideoListAdapter.selectIndex = playIndex - 1

        // 点击关闭
        binding.imageFinsh.setOnClickListener {
            hideActionList()
        }
    }

    private fun hideActionList() {
        binding.layout1.visibility = View.GONE
    }

    private fun showActionList() {
        binding.layout1.visibility = View.VISIBLE
    }
}